package com.maodou.core.ui.components

import androidx.annotation.DrawableRes
import androidx.compose.animation.core.LinearEasing
import androidx.compose.animation.core.animateFloat
import androidx.compose.animation.core.infiniteRepeatable
import androidx.compose.animation.core.rememberInfiniteTransition
import androidx.compose.animation.core.tween
import androidx.compose.foundation.Image
import androidx.compose.foundation.background
import androidx.compose.foundation.clickable
import androidx.compose.foundation.interaction.MutableInteractionSource
import androidx.compose.foundation.layout.*
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.material3.CircularProgressIndicator
import androidx.compose.material3.Divider
import androidx.compose.material3.HorizontalDivider
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.Surface
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.setValue
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.composed
import androidx.compose.ui.draw.rotate
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.res.painterResource
import androidx.compose.ui.text.style.TextAlign
import androidx.compose.ui.unit.Dp
import androidx.compose.ui.unit.dp
import com.google.android.material.progressindicator.CircularProgressIndicator
import kotlinx.coroutines.delay

/**
 * 简单常用 UI 组件封装，方便在编写页面时快速复用。
 *
 * 包含：
 * - VSpacer/HSpacer：占位指定高度/宽度
 * - SizedBox：占用指定宽高区域（空盒子）
 * - AppDivider：水平分割线
 * - AppVerticalDivider：垂直分割线
 * - WeightedSpacer：在 Row/Column 中按权重撑开空间
 */

// 占位：指定高度（常用于垂直方向间距）
@Composable
fun VSpacer(height: Dp, modifier: Modifier = Modifier) {
    Spacer(modifier.then(Modifier.height(height)))
}

// 占位：指定宽度（常用于水平方向间距）
@Composable
fun HSpacer(width: Dp, modifier: Modifier = Modifier) {
    Spacer(modifier.then(Modifier.width(width)))
}

// 占位：指定宽高的空盒子
@Composable
fun SizedBox(width: Dp, height: Dp, modifier: Modifier = Modifier) {
    Box(modifier = modifier.size(width = width, height = height))
}

// 水平分割线（默认 1.dp 厚度，颜色使用主题的 outlineVariant）
@Composable
fun AppDivider(
    modifier: Modifier = Modifier,
    color: Color = MaterialTheme.colorScheme.outlineVariant,
    thickness: Dp = 1.dp,
    startIndent: Dp = 0.dp
) {
    HorizontalDivider(
        modifier = modifier,
        color = color,
        thickness = thickness,
    )
}

// 垂直分割线（通过背景色实现，兼容性更好）
@Composable
fun AppVerticalDivider(
    modifier: Modifier = Modifier,
    color: Color = MaterialTheme.colorScheme.outlineVariant,
    width: Dp = 1.dp,
    height: Dp? = null
) {
    val base = if (height != null) Modifier.height(height) else Modifier.fillMaxHeight()
    Spacer(
        modifier = modifier
            .then(base)
            .width(width)
            .background(color)
    )
}

// 在 Row 中按权重占位，常用于两端对齐或推挤布局
@Composable
fun RowScope.WeightedSpacer(weight: Float = 1f) {
    Spacer(
        modifier = Modifier
            .weight(weight)
            .fillMaxHeight()
    )
}

// 在 Column 中按权重占位
@Composable
fun ColumnScope.WeightedSpacer(weight: Float = 1f) {
    Spacer(
        modifier = Modifier
            .weight(weight)
            .fillMaxWidth()
    )
}

fun Modifier.debouncedClickable(enabled: Boolean = true,  delay: Long = 300,onClick: () -> Unit,) =
    composed {
        var clicked by remember { mutableStateOf(!enabled) }
        LaunchedEffect(key1 = clicked, block = {
            if (clicked) {
                delay(delay)
                clicked = !enabled
            }
        })

        Modifier.clickable(
            enabled = if (enabled) !clicked else false,
            interactionSource = remember { MutableInteractionSource() },
            indication = null
        ) {
            clicked = !clicked
            onClick()
        }

    }

// =================== Loading 组件 ===================
@Composable
fun AppLoadingOverlay(
    visible: Boolean,
    modifier: Modifier = Modifier,
    text: String = "数据加载中",
    panelSize: Dp = 120.dp,
    cornerRadius: Dp = 12.dp,
    scrimColor: Color = MaterialTheme.colorScheme.scrim.copy(alpha = 0.28f),
    containerColor: Color = MaterialTheme.colorScheme.onSurface.copy(alpha = 0.85f),
    indicatorColor: Color = Color.White,
    textColor: Color = Color.White,
    @DrawableRes iconRes: Int? = null,
    imageSize: Dp = 36.dp,
    rotationDurationMillis: Int = 1200,
) {
    if (!visible) return

    Box(
        modifier = Modifier
            .fillMaxSize()
            .background(scrimColor)
            .debouncedClickable {  }
            .then(modifier),
        contentAlignment = Alignment.Center
    ) {
        Column(
            modifier = Modifier
                .size(panelSize).background(color = containerColor, shape = RoundedCornerShape(cornerRadius)),
            horizontalAlignment = Alignment.CenterHorizontally,
            verticalArrangement = Arrangement.spacedBy(12.dp, Alignment.CenterVertically)
        ) {
            if (iconRes != null) {
                val infinite = rememberInfiniteTransition(label = "loading-rotation")
                val angle by infinite.animateFloat(
                    initialValue = 0f,
                    targetValue = 360f,
                    animationSpec = infiniteRepeatable(
                        animation = tween(durationMillis = rotationDurationMillis, easing = LinearEasing)
                    ),
                    label = "angle"
                )
                Image(
                    painter = painterResource(id = iconRes),
                    contentDescription = null,
                    modifier = Modifier
                        .size(imageSize)
                        .rotate(-angle)
                )
            } else {
                CircularProgressIndicator(color = indicatorColor, strokeWidth = 3.dp)
            }
            Text(
                text = text,
                color = textColor,
                style = MaterialTheme.typography.bodySmall,
                textAlign = TextAlign.Center
            )
        }
    }
}
